<template>
	<view class="root">
		<text :style="{ margin: `40rpx 30rpx` }" class="fs-28">
			<text class="color-e60012">*</text>
			<text class="color-1b1b1b">请拍摄合影进行上传</text>
		</text>
		<view class="photos fd-row flex-wrap">
			<image
				v-for="(src, index) in photos"
				:key="index"
				class="bgc-eee br-10"
				:src="src"
				mode="aspectFill"
			/>
			<image
				v-if="photos.length < count"
				@click="choosePhotos"
				class="br-10"
				src="/static/images/pic-uploadPhoto.png"
				mode="aspectFill"
			/>
		</view>
		<button
			:plain="true"
			hover-class="tap-hover"
			class="mt-60 ml-30 mr-30 border-none bgc-3ec483 color-fff fs-30 br-10 lh-3"
			@click="confirmCompleted"
		>
			确认完成
		</button>
	</view>
</template>

<script lang="ts">
	import { Vue, Component } from "vue-property-decorator";
	import { $config } from "@/common";
	import { Storage } from "@/libs/utils";

	@Component
	export default class GroupPhoto extends Vue {
		// component property
		photos: string[] = [];
		count: number = 9;
		order_id: number = 0;
		order_type: number = 0;

		onLoad({ order_id, order_type }: AnyObject) {
			this.order_id = +order_id;
			this.order_type = +order_type;
		}

		choosePhotos() {
			const count = this.count - this.photos.length;
			if(count <= 0) return;

			uni.chooseImage({
				count,
				success: ({ tempFilePaths }) => this.photos.push(...tempFilePaths),
			});
		}
		confirmCompleted() {
			if (!this.photos.length) return;

			uni.showToast({ title: "uploading...", icon: "loading" });
			const uploads: string[] = [];

			const submit = () => {
				this.$request
					.get("/order/photo", {
						id: this.order_id,
						type: this.order_type,
						images: uploads.toString(),
					})
					.then(({ errmsg: title }) =>
						uni.showToast({
							title,
							success: () => setTimeout(uni.navigateBack, 1500),
						})
					);
			};

			this.photos.forEach(async (filePath) => {
				const [uploadFail, uploadRes]: any = await uni.uploadFile({
					url: $config.API_URL + "/upload",
					filePath,
					name: "file",
					header: {
						Authorization: Storage.get("authorization").access_token,
					},
				});

				if (uploadFail) {
					uni.showToast({
						title: uploadFail.errMsg,
						icon: "none",
					});
					return;
				}

				const { errcode, errmsg: title, data } = JSON.parse(uploadRes.data);

				if (errcode) {
					uni.showToast({
						title,
						icon: "none",
					});
					return;
				}
				uploads.push(data.img);

				uploads.length === this.photos.length && submit();
			});
		}
	}
</script>

<style lang="scss" scoped>
	// scss
	.photos {
		margin: 0 24rpx;
		image {
			width: 164rpx;
			height: 164rpx;
			margin: 6rpx;
		}
	}
</style>